import React, { Component } from 'react';
import CustomForm from '../../../../components/CustomForm';
import { Select, Button } from 'antd';
import services from '../../../../services/api';
import Modal from '../../../../components/Modal/index';
import AddCaseType from '../../RiskCase/add';
import { randomKey } from '../../../../utils/utils';

const { Option } = Select;

class selectCaseType extends Component {
  constructor(props) {
    super(props);
    this.state = {
      caseTypes: [],
    };
    this.api = 'caseApi';
    this.form = null;
    this.key = null
  }

  componentDidMount() {
    this.getCaseTypeList();
  }

  getCaseTypeList = () => {
    services[this.api].type().then((res) => {
      if (res.code === 0) {
        this.setState({
          caseTypes: res.data,
        });
      }
    });
  };

  handleAddCaseType = () => {
    this.key = randomKey()
    Modal.open({
      title: '添加案件分类',
      width: '500px',
      content: (
        <AddCaseType
          colNum={1}
          closeModal={this.closeAddCaseModal}
          case_id={[this.state.case_id]}
          actionType='add'
        />
      ),
      isOkBtn: false,
      maskClosable: false,
      isCancelBtn: false,
      key: this.key
    });
  };

  closeAddCaseModal = (onlyClose) => {
    if (onlyClose === true) {
      Modal.close(this.key)
    } else {
      Modal.close(this.key)
      this.getCaseTypeList();
    }
  };

  handleSubmit = () => {
    this.form.validateFields((err, values) => {
      if (!err) {
        this.props.handleSubmit(values.case_category_id)
        this.props.closeModal(true)
      }
    });
  };

  render() {
    const formItems = [
      {
        label: {
          label: '案件分类',
          className: 'tantuer-form-item3 tantuer-form-item-nowrap',
        },
        name: 'case_category_id',
        options: {
          rules: [{ required: true, message: '请选择' }],
        },
        component: (
          <Select placeholder='请选择' style={{ width: '300px' }}>
            {(this.state.caseTypes || []).map((item, index) => {
              return (
                <Option value={item.case_category_id} key={item.case_category_id}>
                  {item.case_category_name}
                </Option>
              );
            })}
          </Select>
        ),
        after: (
          <Button type='primary' onClick={this.handleAddCaseType}>
            添加案件分类
          </Button>
        ),
      },
    ].filter(Boolean);

    return (
      <CustomForm
        closeModal={() => this.props.closeModal(true)}
        createForm={ref => (this.form = ref)}
        formItems={formItems}
        onHandleSubmit={this.handleSubmit}
        colNum={1}
      />
    );
  }
}

export default selectCaseType;
